const Router = require('koa-router')
const bcryptjs = require('bcryptjs')
const { ParameterError } = require('../../config/errorCode')
const { generateToken, generateRefreshToken, CustomError, setCookie, Success } = require('../../core/common')
const {User} = require('../../model/index')
const router = new Router({
  prefix: '/v1/login'
})
// 验证码登入
router.get('/vcodeLogin', (ctx, next) => {
  ctx.body = {
    status: 'ok'
  }
})
// 账号密码登入
router.post('/accountPasswordLogin', async (ctx) => {
  const { phone, password } = ctx.request.body
  const user = await User.findOne({ where: { phone } })
  if (!user) {
    throw new CustomError('手机号未注册', ParameterError)
  }
  const isPasswordCorrect = bcryptjs.compareSync(password, user.password)
  if (!isPasswordCorrect) {
    throw new CustomError('密码错误', ParameterError)
  }
  const token = generateToken(user.uid)
  const refreshToken = generateRefreshToken(user.uid)
  // 服务端渲染时无法使用localStorage，使用cookie代替
  setCookie(ctx, 'access_token', token)
  setCookie(ctx, 'refresh_token', refreshToken)

  Success(ctx,user.userInfo)
})

module.exports = router
